//
//  HRComposeView.swift
//  weiBo
//
//  Created by helong on 16/7/16.
//  Copyright © 2016年 helong. All rights reserved.
//

import UIKit
/// 微博compose的页面
class HRComposeView: UIView {
    //  存储传递过来的控制器用来完成界面的跳转
    private var controller: UITabBarController?
    //  存储按钮的数组
    var composeButtonArray = [HRComposeButton]()
    //  按钮信息的模型数组
    var composeArray = [HRCompose]()
    //  懒加载遮罩图片
    private lazy var coverImageView: UIImageView = {
        //  创建cover,并给其添加一个磨砂遮罩(具体方法参考UIimage的分类)
    let cover = UIImageView(image: UIImage.getScreenShot().applyLightEffect())
        return cover
    }()
    //  懒加载底部状态按钮
    private lazy var statusButton: UIButton = {
        let btn = UIButton()
        btn.setImage(UIImage(named: "tabbar_compose_background_icon_close"), forState: .Normal)
        //  取消按钮的高亮显示
        btn.adjustsImageWhenHighlighted = false
        btn.backgroundColor = UIColor.whiteColor()
        btn.addTarget(self, action: "dismissComposeView:", forControlEvents: .TouchUpInside)
        return btn
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
     // MARK: - 添加子控件,设置UI约束
    private func setupUI(){
        //  设置遮罩视图大小
        self.frame.size = CGSize(width: screenWidth(), height: screenHeight())
        addSubview(coverImageView)
        //  设置遮罩image的约束
        coverImageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(self).offset(UIEdgeInsetsZero)
        }
         addSubview(statusButton)
        
        statusButton.snp_makeConstraints { (make) -> Void in
            make.leading.equalTo(self)
            make.trailing.equalTo(self)
            make.bottom.equalTo(self)
            make.height.equalTo(100)
            
        }
//        self.bounds = UIScreen.mainScreen().bounds
//        backgroundColor = randomColor()
        
//        let image = UIImage.getScreenShot()
//        //  把图片存储到本地的方法
//        UIImagePNGRepresentation(image)?.writeToFile("/Users/helong/Desktop/登录/111.png", atomically: true)
        
        
        //  获得按钮信息
        composeButtonInfo()
        //   添加按钮的方法
        addComposeButton()
    }
     // MARK: - 底部按钮的点击事件
    @objc private func dismissComposeView(sender: UIButton){
        print("我被点击了")
        //  旋转底部按钮
        UIView.animateWithDuration(1) { () -> Void in
            
            sender.imageView?.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
        }
        //  状态按钮消失
        
        //  遮罩消失
    }
     // MARK: - 添加按钮的方法
    private func addComposeButton(){
        let buttonHeight: CGFloat = 110
        let buttonWidth: CGFloat = 80
        let margin = (screenWidth() - buttonWidth * 3) / 4
        
        for (i, value) in composeArray.enumerate() {
            
            let cols = i % 3
            let rows = i / 3
            let btn = HRComposeButton()
            //  设置控件大小
            btn.bounds.size = CGSize(width: buttonWidth, height: buttonHeight)
            btn.x = margin * CGFloat(cols + 1) + buttonWidth * CGFloat(cols)
            //  先让按钮的顶部与屏幕的底部对齐,然后做动画显示按钮
            btn.y = (margin + buttonWidth) * CGFloat(rows) + screenHeight()
            //  给空间赋值
            btn.setImage(UIImage(named: composeArray[i].icon!), forState: .Normal)
            btn.setTitle(composeArray[i].title, forState: .Normal)
            addSubview(btn)
            //  绑定按钮点的模型
            btn.composeModel = value

            //  给按钮添加点击事件
            btn.addTarget(self, action: "composeAction:", forControlEvents: .TouchUpInside)
            
            composeButtonArray.append(btn)
        }
        

    }
     // MARK: - compose 按钮的点击事件
    @objc private func composeAction(sender: HRComposeButton){
        print("clicked")

        //  根据字符串生成跳转控目标制器
        let targetVCType = NSClassFromString((sender.composeModel?.targetViewController)!) as! UIViewController.Type
        let targetVC = targetVCType.init() as! HRComposeController
        targetVC.fatherView = self
        //  将视图包装在导航控制器中
        let nav = UINavigationController(rootViewController: targetVC)
        
        for value in composeButtonArray {
            if value == sender {
        buttonScaleAnimation(value, nav: nav,scale: 3, willPresent: true)
            }else {
                buttonScaleAnimation(value, nav: nil,scale: 0.5, willPresent: false)
            }
        }
    }
     // MARK: - 按钮点击的动画
    /**
    自定义点击按钮的缩放动画
    
    - parameter sender:      要执行缩放的按钮
    - parameter nav:         要跳转的布标控制器
    - parameter scale:       缩放的比例
    - parameter willPresent: 被点击的按钮是否执行跳转控制器
    */
    private func buttonScaleAnimation(sender: HRComposeButton, nav: UINavigationController?, scale: CGFloat, willPresent: Bool){
        //  被点击的按钮放大,没有被点击的按钮缩小,然后还原
        UIView.animateWithDuration(0.25, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 10, options: .LayoutSubviews, animations: { () -> Void in
            sender.transform = CGAffineTransformMakeScale(scale, scale)
            //  如果动画按钮不用跳转控制器,改变其透明度
            if !willPresent {
                sender.alpha = 0.2
            }
            }) { (_) -> Void in
                UIView.animateWithDuration(0.25, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 10, options: .LayoutSubviews, animations: { () -> Void in
                    sender.transform = CGAffineTransformIdentity
                    }, completion: { (_) -> Void in
                        //  如果动画按钮要跳转控制器
                        if willPresent {
                        //  跳转控制器
                        self.controller!.presentViewController(nav!, animated: true, completion: nil)
                        }
                        sender.alpha = 1
                        
                })
        }
  
    }
     // MARK: - 字典转模型
    private func composeButtonInfo(){
        //  获取路径
        let path = NSBundle.mainBundle().pathForResource("ComposeButton.plist", ofType: nil)
        //  要用NSArray  因为array没有这个方法
       let arr = NSArray(contentsOfFile: path!)
        var tempArr = [HRCompose]()
        for dict in arr! {
           let compose = HRCompose(dict: dict as! [String : AnyObject])
            tempArr.append(compose)
        }
        composeArray = tempArr
    }
     // MARK: - 显示按钮的动画
    func show(FromController: UITabBarController){
        controller = FromController
//        guard let window = UIApplication.sharedApplication().windows.last else {
//            return
//        }
        //  将遮罩添加在父视图上,  注意:  如果添加在window上不能点击跳转??????????编译环境问题
        FromController.view.addSubview(self)
        //  按钮的弹出动画
        for (i, value) in composeButtonArray.enumerate() {
           startAnimation(value, i: i, isUp: true)
        }
        

        
    }
     // MARK: - 使用pop框架完成pop动画
    
    
     // MARK: - 使用dispatch的方法完成pop动画
    private func startAnimation(value: UIButton, i: Int, isUp: Bool) {
        let delay = 0.1 * Double(i)

        
        let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC)))
        dispatch_after(delayTime, dispatch_get_main_queue()) { () -> Void in
            
            UIView.animateWithDuration(1, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 5, options: .LayoutSubviews, animations: { () -> Void in
                if isUp {
                    
                    value.center.y -= 350
                }else{
                    value.center.y += 350
                }
                self.layoutIfNeeded()
                }, completion: nil)
        }

    }
     // MARK: - 点击屏幕遮罩消失
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        //  移除遮罩
       let reversedComposeButtonArray = composeButtonArray.reverse()
        for (i, value) in reversedComposeButtonArray.enumerate() {
            startAnimation(value, i: i, isUp: false)
        }
        let delay = dispatch_time(DISPATCH_TIME_NOW, Int64(1 * NSEC_PER_SEC))
        dispatch_after(delay, dispatch_get_main_queue()) { () -> Void in
            
            self.removeFromSuperview()
        }
    }
    
   
}
